package com.bjpowernode.handler;

import cn.hutool.json.JSONUtil;
import com.bjpowernode.constant.Constant;
import com.bjpowernode.entity.TUser;
import com.bjpowernode.result.R;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 退出成功后执行这个handler
 */
@Component
public class AppLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        //退出登录成功后，除了spring security框架自己会清理认证信息外，还要把redis中的token删除
        //获取当前登录用户
        TUser user = (TUser) authentication.getPrincipal();
        Integer id = user.getId();
        redisTemplate.opsForHash().delete(Constant.REDIS_TOKEN_KEY,id.toString());
        R result = R.ok("退出成功",authentication);
        String json = JSONUtil.toJsonStr(result);
        response.getWriter().write(json);
    }
}
